package com.derbysoft.dswitch.adapter.ihg.dswitch3.translate.impl;

import com.derbysoft.dswitch.adapter.ihg.dto.CancelPenalty;
import com.derbysoft.dswitch.adapter.ihg.dto.GuestCount;
import com.derbysoft.dswitch.adapter.ihg.dto.Rate;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

public abstract class TranslateHelper {
    public static final Integer GUEST_TYPE_ADULT = 10;
    public static final Integer GUEST_TYPE_CHILD = 8;
    private static final String LONG_TIME = "999";

    public static final Map<String, String> NO_SHOW_PENALTY = new HashMap<String, String>();

    static {
        NO_SHOW_PENALTY.put("NUMBER_OF_NIGHTS", "1N");
        NO_SHOW_PENALTY.put("ENTIRE_STAY", "100P");
        NO_SHOW_PENALTY.put("FIRST_NIGHT", "1N");
    }

    public static GuestCount createChildGuestCount(Integer count) {
        GuestCount guestCount = new GuestCount();
        guestCount.setAgeQualifyingCode(GUEST_TYPE_CHILD);
        guestCount.setCount(count);
        return guestCount;
    }

    public static GuestCount createAdultGuestCount(Integer count) {
        GuestCount guestCount = new GuestCount();
        guestCount.setAgeQualifyingCode(GUEST_TYPE_ADULT);
        guestCount.setCount(count);
        return guestCount;
    }

    public static String convertPenaltyCode(Rate ihgRate) {
        String noShowPenalty = NO_SHOW_PENALTY.get(ihgRate.getTPAExtensions().getCxlBasisType().getValue().toUpperCase());
        CancelPenalty cancelPenalty = ihgRate.getCancelPolicies().getCancelPenalty().get(0);
        if (cancelPenalty.getDeadline() == null) {
            return null;
        }

        if (StringUtils.isNotBlank(cancelPenalty.getDeadline().getOffsetTimeUnit())
                && cancelPenalty.getDeadline().getOffsetTimeUnit().equals("Day")) {
            if (cancelPenalty.getDeadline().getOffsetUnitMultiplier().equals(LONG_TIME)) {
                return String.format("AD%s_%s", noShowPenalty, noShowPenalty);
            }
            return String.format("%sD%s_%s", cancelPenalty.getDeadline().getOffsetUnitMultiplier(), noShowPenalty, noShowPenalty);
        }

        if (StringUtils.isNotBlank(cancelPenalty.getDeadline().getAbsoluteDeadline())) {
            String[] dateTime = StringUtils.split(cancelPenalty.getDeadline().getAbsoluteDeadline(), "T");
            if (dateTime != null && dateTime.length == 2) {
                short hourOfDay = Short.parseShort(StringUtils.split(dateTime[1], ":")[0]);
                if (hourOfDay > 12) {
                    return String.format("%sPM0D100P_100P", hourOfDay - 12);
                } else {
                    return String.format("%sAM0D100P_100P", hourOfDay);
                }
            }
        }
        return null;
    }
}
